import numpy as np
import cv2
import threading
from decode import h264_decode
from host import host
from udp3 import udp_client7, udp_client9

detected_circles_list = []  # 用于存储所有线程中的 detected_circles
lock = threading.Lock()  # 创建一个锁对象


def process_image(frame):
    global detected_circles
    global lock
    i = 0
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray_blur = cv2.GaussianBlur(gray, (5, 5), 0)
    circles = cv2.HoughCircles(gray_blur, cv2.HOUGH_GRADIENT_ALT, 1.5, 30, param1=200, param2=0.8, minRadius=100, maxRadius=350)
    with lock:
        detected_circles = []
    if circles is not None:
        circles = np.round(circles[0, :]).astype("int")
        with lock:
            print('返回位置：',circles)
            if i == 0:
                i = 1
                data_dict = {'x': circles[0][0], 'y': circles[0][1], 'r': circles[0][2]}
                data_str = 'x:{x},y:{y},r:{r}'.format(**data_dict)
                packet = bytes(data_str, encoding='utf-8')
                udp_client9.sendto(packet, (host, 4001))

            detected_circles = circles[0].tolist()
            detected_circles_list.append(detected_circles)
        cv2.circle(frame, (circles[0][0], circles[0][1]), circles[0][2], (0, 255, 0), 2)
        cv2.circle(frame, (circles[0][0], circles[0][1]), 2, (0, 255, 0), 3)
    return frame


if __name__ == '__main__':
    while True:
        data, addr =udp_client7.recvfrom(4096)
        frames = h264_decode(b'' + data)
        for frame in frames:
            frame = np.array(frame)
            t = threading.Thread(target=process_image, args=(frame,))
            t.start()
            t.join()  # 等待线程处理完成
            cv2.imshow("Camera", frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
